# -*- coding: utf-8 -*-
__author__ = 'sunnychou'
__date__ = '2019/9/22 10:55'
from common.logger_helper import g_wlogger
'''
k3的数据报表主入口
'''
from k3_data_report.config  import  DRP_TJ_YW_PROCESS_DICT, DRP_TJ_CW_PROCESS_DICT
from common.pandas_helper import PandasHelper
from common.email_helper import email_send_with_appendix_list
from k3_data_report.config import EMAIL_FILE_DIR

def tj_process_item(tjmonth, create_df_fun, excel_name):
    try:
        tj_proc_df = create_df_fun(tjmonth)
        if tj_proc_df.empty:
            g_wlogger.warning(f"tj_process_item create_df_fun is empty with excel_name:{excel_name}")
            return False
        # 2. 写excel
        PandasHelper.df_to_excel(tj_proc_df, f"{EMAIL_FILE_DIR}" + "\\" + f"{excel_name}{tjmonth}.xls")
        return True
    except Exception as e:
        g_wlogger.werror(f"tj_process_item has error:{e} with excel_name:{excel_name}")
        return False

def process_final_report(tjmonth, process_dict, ptype="业务中心报表"):
    # 业务中心处理
    dp_excel_list = []
    for tj_proc_key in process_dict.keys():
        tj_proc_list = process_dict[tj_proc_key]
        # excel_list = [tj_process_item(tjmonth, create_df_fun, excel_name)   for (create_df_fun, excel_name) in  tj_proc_list]
        for (create_df_fun, excel_name) in tj_proc_list:
            print(f"start to process excel_name:{excel_name} with month:{tjmonth}")
            if not tj_process_item(tjmonth, create_df_fun, excel_name):
                print("tj_process_item return false")
                continue
            mstr = f"finish process excel_name:{excel_name}, {tj_proc_key} with month:{tjmonth}"
            print(mstr)
            g_wlogger.winfo(mstr)
            dp_excel_list.append(excel_name)
    # 业务中心报表批量发送邮件
    subject = f"{ptype}-{tjmonth}"  # 邮件主题
    mail_msg = f"您好：\n 请您关注{ptype}报表，详细报表见附件，谢谢！"  # 邮件主体部分内容，可以写成html格式

    appendix_files = [f"{EMAIL_FILE_DIR}" + "\\" + f"{dp_excel}{tjmonth}.xls" for dp_excel in dp_excel_list]
    email_send_with_appendix_list(subject, mail_msg, appendix_files)


def k3_final_report_process(tjmonth):
    '''
    需要进行合并后的最终excel数据报表功能
    :param tmonth: 待统计的月份
    :return:
    '''
    try:
        #业务中心报表
        process_final_report(tjmonth, DRP_TJ_YW_PROCESS_DICT, "业务中心报表邮件")

        #财务中心报表
        process_final_report(tjmonth, DRP_TJ_CW_PROCESS_DICT, "财务中心报表邮件")

    except Exception as e:
        g_wlogger.werror(f"k3_final_report_process has error with:{tjmonth} error:{e}")





if  __name__ == "__main__":
    month = "2019-08"
    k3_final_report_process(month)
